package com.hopu.blb_erp.controller;

import com.hopu.blb_erp.entity.Assist;
import com.hopu.blb_erp.entity.UserRole;
import com.hopu.blb_erp.service.RoleService;
import com.hopu.blb_erp.service.UserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@Api
@RestController
public class UserRoleController {

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RoleService roleService;

    @ApiOperation("修改用户角色")
    @PostMapping( "/user-role")
    public ResponseEntity<String> modifyUserRole(@RequestBody Assist assist) {
        // 角色名
        String[] roleName = assist.getRoleName();
        // 用户id
        Long id = assist.getId();
        // 将用户角色清空
        userRoleService.remove(id);
        // 对用户的角色进行添加和删除操作
        for (int i = 0; i < roleName.length; i++) {
            UserRole userRole = new UserRole();
            // 查询角色对应的id
            Long roleId = roleService.findRoleName(roleName[i]);
            userRole.setRoleId(roleId);
            userRole.setUserId(id);
            // 给用户添加角色
            userRoleService.add(userRole);
        }
        return ResponseEntity.ok("ok");
    }
}
